package com.ctsi.framework.mybatis.support;

import com.ctsi.commons.util.UtilValidate;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.dao.support.DaoSupport;

import java.util.List;

import static org.springframework.util.Assert.notNull;

/**
 * 批量操作，支持增加、删除，需要注入批量SqlSessionTemplate
 * 
 * @author zhangjw
 *
 */
public class MybatisBatchDao extends DaoSupport {

	private SqlSessionTemplate sqlSessionTemplate;

	public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
		this.sqlSessionTemplate = sqlSessionTemplate;
	}
	/**
	 * 批量添加
	 * 
	 * @param entityClass
	 * @param oList
	 * @return 返回受到影响记录的条数
	 */
	public int batchInsert(Class<?> entityClass, final List<?> oList) {
		if (UtilValidate.isEmpty(oList)) {
			return 0;
		}
		final String mapperStr = entityClass.getName() + MybatisGenericDao.POSTFIX_INSERT;
		int result = 0;
		for (Object o : oList) {
			result+=sqlSessionTemplate.insert(mapperStr, o);
		}
		return result;
	}

	public int batchRemove(Class<?> entityClass, List<?> dList) {
		if (UtilValidate.isEmpty(dList)) {
			return 0;
		}
		final String mapperStr = entityClass.getName() + MybatisGenericDao.POSTFIX_DELETE;
		int result = 0;
		for (Object o : dList) {
			result += sqlSessionTemplate.delete(mapperStr, o);
		}
		return result;
	}

	@Override
	protected void checkDaoConfig() throws IllegalArgumentException {
		notNull(this.sqlSessionTemplate, "Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required");
	}
}
